import $cookies from 'js-cookie';

/**
 * cookie 名称
 * @type {string}
 */
const COOKIE_NAME = 'uat';
//  初始化 state
const state = {
    /**
     * 访问令牌
     */
    accessToken : $cookies.get(COOKIE_NAME)
};

const getters = {
    getAccessToken : state => state.accessToken
};

//  匹配Ip的正则表达式
const PATTERN = /(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)/;

const mutations = {
    setAccessToken(state,accessToken){
        state.accessToken = accessToken;
        if (null === accessToken){
            $cookies.remove(COOKIE_NAME);
            return;
        }
        //  判断当前浏览器地址是否为Ip
        let domain = window.location.hostname;
        if (!PATTERN.test(domain)) {
            domain = domain.split('.').slice(-2).join('.');
        }
        $cookies.set(COOKIE_NAME, accessToken , 0, '/', domain);
    },
};

const actions = {

};

export default {
    state : state,
    getters : getters,
    mutations : mutations,
    actions : actions
};
